package com.budayi.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author LIBOFEI
 * @ClassName MyFilter
 * @description 实现网关的自定义过滤器
 * @date 2020/9/12 15:38
 * @Version 1.0
 **/
@Component
public class MyFilter extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(MyFilter.class);

    /** *
     filterType即指定过滤器的类型，一共有四种类型，分别是 pre,post,routing,error
    **/
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /** *
     filterOrder即过滤顺序，int值越小，越早执行该过滤器
     **/
    @Override
    public int filterOrder() {
        return 0;
    }

    /** *
     shouldFilter表示该过滤器是否过滤逻辑，如果为true，则执行run方法，如果为false，则不执行run方法
    **/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /** *
    run方法写具体的过滤逻辑，在本例中检查是否传了token参数，如果没有传，直接返回401响应码
    **/
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        Object token = request.getParameter("token");
        if(token == null){
            logger.warn("from " + request.getRemoteAddr() + " request token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try{
                ctx.getResponse().getWriter().write("token is empty");
            }catch(Exception e){
                return null;
            }
        }
        logger.info("from " + request.getRemoteAddr() + "is Ok");
        return null;
    }
}
